home *** CD-ROM | disk | FTP | other *** search
/ Ian & Stuart's Australian Mac: Not for Sale / Another.not.for.sale (Australia).iso / Dr. Doyle / C Lesson / C-LESSON.9 < prev   
Text File  |  1993-11-08  |  14KB  |  434 lines

  1.  
  2.                                  Lesson 8.
  3.  
  4.   This lesson and the following one will examine how to use the program
  5. structure - as opposed to data structure - reserved words.
  6.  
  7.   Lets start with the looping structures:
  8.  
  9.   do repeated_statement while ( logical_expression );
  10.  
  11.   repeated_statement, which may be a block of code, will be executed
  12. repetitively until the logical_expression, becomes false. If you have been
  13. exposed to ( corrupted by? ) another language remember that there is no
  14. `until' test at the end of a loop. Note that the repeated_statement is always
  15. executed once irrespective of the state of the logical_expression.
  16.  
  17.   while ( logical_expression ) repeated_statement;
  18.  
  19.   repeated_statement is executed repetitively while the logical_expression
  20. is true. Once again statement may be a block of code. Note that if the
  21. logical_expression evaluates to FALSE then the repeated_statement is NEVER
  22. executed.
  23.  
  24.   Associated with the looping structures are the control words:
  25.  
  26.   break;
  27.   continue;
  28.  
  29.   break; allows you to leave a loop in the middle of a block, and
  30.   continue; allows you to re-start it from the top.
  31.  
  32.   Finally we must not forget the most common and useful looping construct:
  33.  
  34.   for ( initialising statement; logical_expression; incremental_statement )
  35.   repeated_statement;
  36.  
  37.   Some further explanation is needed. The initialising statement is
  38. executed once, but to allow for the need to initialise several separate
  39. variables the assignment statements may be separated by commas. The
  40. logical_expression must be true for the loop to run, and the
  41. incremental_statement is executed once each time the loop is run.
  42. The for statement is completely general and may, for example, be used to
  43. manipulate a set of pointers to operate on a linked list.
  44.  
  45. Some examples.
  46.  
  47.   A do loop program.
  48.  
  49. #ident "@(#) do_demo.c - An example of the do loop"
  50.  
  51. #include <stdio.h>
  52.  
  53. main()
  54. {
  55.   char character;
  56.  
  57.   character = 'a';
  58.  
  59.   do printf ( "%c", character ); while ( character++ < 'z' );
  60.   printf ( "\n" );
  61.   }
  62.  
  63.   Fairly obviously it prints:
  64.  
  65. abcdefghijklmnopqrstuvwxyz
  66.  
  67.   A while loop example.
  68.  
  69. #ident "@(#) while_demo.c - An example of the while loop"
  70.  
  71. #include <stdio.h>
  72.  
  73. main()
  74. {
  75.   char character;
  76.  
  77.   character = 'a';
  78.  
  79.   while ( character <= 'z' ) printf ( "%c", character++ );
  80.   printf ( "\n" );
  81.   }
  82.  
  83.   Its output is exactly the same as the previous example:
  84.  
  85. abcdefghijklmnopqrstuvwxyz
  86.  
  87.   In this totally trivial case it is irrelevant which program structure
  88.   you use, however you should note that in the `do' program structure the
  89.   repeated statement is always executed at least once.
  90.   A for loop example.
  91.  
  92.   The `for' looping structure.
  93.  
  94. #ident "@(#) for_demo.c - An example of the for loop"
  95.  
  96. #include <stdio.h>
  97.  
  98. main()
  99. {
  100.   char character;
  101.  
  102.   for ( character = 'a'; character <= 'z' ; character++ )
  103.   {
  104.     printf ( "%c", character );
  105.     }
  106.   printf ( "\n" );
  107.   }
  108.  
  109.   Surprise, Surprise!
  110.  
  111. abcdefghijklmnopqrstuvwxyz
  112.  
  113.   You should be aware that in all the looping program structures, the
  114. repeated statement can be a null statement ( either just a `;' or the
  115. reserved word `continue;' ). This means that it is possible to - for
  116. example - position a pointer, or count up some items of something or other.
  117. It isn't particularly easy to think up a trivial little program which
  118. demonstrates this concept, however the two `for' loops give some indication
  119. of the idea.
  120.  
  121. #ident "@(#) pointer_demo.c - Pointer operations with the for loop"
  122.  
  123. #include <stdio.h>
  124.  
  125. main()
  126. {
  127.   char character, *character_pointer, alphabets [ 53 ];
  128.  
  129.   for ( character = 'a', character_pointer = alphabets;  /* Start conditions */
  130.         character <= 'z';                                /* Run while true   */
  131.         *character_pointer++ = character++               /* All the work     */
  132.         )TRUE continue;
  133.  
  134.   for ( character = 'A';  /* character_pointer is at the right place already */
  135.         character <= 'Z';
  136.         *character_pointer++ = character++
  137.         ) continue;
  138.  
  139.   *character_pointer = (char) '\000'; /* NULL character to terminate string. */
  140.  
  141.   printf ( "%s\n\n", alphabets );
  142.   }
  143.  
  144.   Another Surprise!
  145.  
  146. abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  147.  
  148.   So much for the looping structures provided by the `C' language. The
  149. other main structures required to program a computer are the ones which
  150. alter the program flow. These are the switch, and the if and its extension
  151. the if ... else combination. More demo programs are much the best way of
  152. getting the message across to you, so here they are, first the if construct.
  153.  
  154. #ident "if_demo.c"
  155.  
  156. #include <stdio.h>
  157.  
  158. main(argc, argv)
  159. int argc;
  160. char **argv;
  161. {
  162.   if ( argc > 1 ) printf ( "You have initiated execution with arguments."};
  163.   }
  164.  
  165.   And the if ... else demo.
  166.  
  167. #ident "if_else_demo.c"
  168. /*
  169. ** The Language #define could go in the compiler invocation line if desired.
  170. */
  171.  
  172. #define ENGLISH
  173.  
  174. #include <stdio.h>
  175.  
  176. /*
  177. ** The message and text fragments output by the program.
  178. */
  179.  
  180. char *messages[] =
  181. {
  182. #if defined( ENGLISH )
  183. #ident "@(#)ENGLISH Version"
  184.   "\nUsage: if_else_demo <numeric argument 1> <numeric argument 2>\n\n",
  185.   "The first argument is ",
  186.   "the second",
  187.   "equal to ",
  188.   "bigger than ",
  189.   "smaller than "
  190. #endif
  191.  
  192. #if defined( FRANCAIS )
  193. #ident "@(#)FRENCH Version"
  194.  
  195.   put the French translation in here so that we are ready to export to
  196.   French speaking Countries. I'd be grateful if a French speaker could
  197.   make the translation for me.
  198.  
  199. #endif
  200.   };
  201.  
  202. /*
  203. ** Meaningful words defined to constants
  204. */
  205.  
  206. #define USAGE 0
  207. #define FIRST 1
  208. #define SECOND 2
  209. #define EQUAL 3
  210. #define BIGGER 4
  211. #define SMALLER 5
  212.  
  213. #define SUCCESS 0
  214. #define FAILURE 1
  215.  
  216. /*
  217. ** We need this more than once so it can be put in a function.
  218. */
  219.  
  220. void usage()
  221. {
  222.   printf ( messages[USAGE]);
  223.   exit ( FAILURE );
  224.   }
  225.  
  226. /*
  227. ** Main program function starts here. ( At the top of a page no less! )
  228. */
  229.  
  230. int main ( argc, argv )
  231. int argc;
  232. char **argv;
  233. {
  234.   int message_index;
  235.   double i, j, strtod();
  236.   char *ptr;
  237.  
  238.   if ( argc != 3 ) usage();                  /* have we been given the right */
  239.                                              /* number of arguments. */
  240.   i = strtod ( argv[1], &ptr);               /* Convert to a double float. */
  241.   if ( ptr == argv[1] ) usage();             /* Successful conversion? */
  242.   j = strtod ( argv[2], &ptr);               /* Convert to a double float. */
  243.   if ( ptr == argv[2] ) usage();             /* Successful conversion? */
  244.  
  245. /*
  246. ** This statement uses the "ternary conditional assignment" language
  247. ** construction to assign the value required to the message indexing variable.
  248. ** Note that this concept is efficient in both the generation of machine code
  249. ** output ( compile the program with a -S switch and have a look ) and in the
  250. ** ease with which it can be understood. The assignment is obvious instead of
  251. ** being buried under a litter of `if' and `else' keywords.
  252. */
  253.  
  254.   message_index = ( i == j ) ? EQUAL : ( i > j ) ? BIGGER : SMALLER;
  255.  
  256. /*
  257. ** Now print the message.
  258. */
  259.  
  260.   (void) printf ( "\n%s%s%s\n\n",     /* Format string specifying 3 strings. */
  261.                   messages[ FIRST ],                   /* Address of string. */
  262.                   messages[ message_index ],           /*        ditto.      */
  263.                   messages[ SECOND ]                   /*        ditto.      */
  264.                   );
  265.   return ( SUCCESS );
  266.   }
  267.  
  268.   Well as you can no doubt gather it simply compares two numbers on the
  269. command line and ejects a little message depending on the relative magnitude
  270. of the numbers. In the UNIX tradition the help message is perhaps somewhat
  271. terse, but it serves the purpose of getting you - the student - to think
  272. about the importance of creating programs which always cope with nonsensical
  273. input in a civilised way. Here are the lines of output.
  274.  
  275. Usage: if_else_demo <numeric argument 1> <numeric argument 2>
  276.  
  277. The first argument is equal to the second
  278.  
  279. The first argument is smaller than the second
  280.  
  281. The first argument is bigger than the second
  282.  
  283.   Now that the international community is shrinking with vastly improved
  284. telecommunications, it is perhaps a good idea to think carefully about
  285. creating programs which can talk in many languages to the users. The method
  286. of choice is - I believe - that presented above. The #if defined( LANGUAGE )
  287. gives us an easy method of changing the source code to suit the new sales
  288. area. Another possibility is to put all the text output needed from a program
  289. into a file. The file would have to have a defined layout and some consistent
  290. way of `getting at' the message strings.
  291.  
  292.   From a commercial point of view this may or may not be a good business plan.
  293. Quite definitely it is an absolute no no to scatter a mass of string literals
  294. containing the messages and message fragments all over your program script.
  295.  
  296.   There are two more methods of altering the program flow.
  297.  
  298.   1 ) The goto a label.
  299.   2 ) The setjump / longjmp library routines.
  300.  
  301.   The concept of the go to a label construction has had reams of literary
  302. verbiage written about it and this author does not intend to add to the pile.
  303. Suffice it to say that a goto is a necessary language construct. There are a
  304. few situations which require the language to have ( in practice ) some form of
  305. unconditional jump. Treat this statement with great caution if you wish your
  306. code to be readable by others. An example of legitimate use.
  307.  
  308.   for ( a = 0; a < MATRIX_SIZE; a++ )
  309.   {
  310.     for ( b = 0; b < MATRIX_SIZE; b++ )
  311.     {
  312.       if ( process ( matrix, a, b )) goto bad_matrix;
  313.       }
  314.      }
  315.    return ( OK );
  316.  
  317. bad_matrix:
  318.  
  319.    perror ( progname, "The data in the matrix seems to have been corrupted" );
  320.    return ( BAD );
  321.  
  322.   This is one of the very few "legitimate" uses of goto, as there is no
  323. "break_to_outer_loop" in `C'. Note that some compilers complain if the label
  324. is not immediately followed by a statement. If your compiler is one of these
  325. naughty ones, you can put either a `;' or a pair of braces `{}' after the
  326. `:' as a null statement.
  327.  
  328.   An example of a program package which makes extensive use of the goto is the
  329. rz and sz modem communications protocol implementation by Chuck Forsberg of
  330. Omen Technology. You should download it and study the code, but do remember
  331. that the proof of the pudding argument must apply as the rz & sz system has
  332. become extremely popular in its application because it works so well.
  333.  
  334.   The other method of changing program flow is the setjump and longjmp pair of
  335. library functions. The idea is to provide a method of recovery from errors
  336. which might be detected anywhere within a large program - perhaps a compiler,
  337. interpreter or large data acquisition system. Here is the trivial example:
  338.  
  339. #ident "set_jmp_demo.c"
  340.  
  341. #include <stdio.h>
  342. #include <setjmp.h>
  343.  
  344. jmp_buf save;
  345.  
  346. main()
  347. {
  348.   char c;
  349.  
  350.   for ( ;; )                     /* This is how you set up a continuous loop.
  351. */
  352.   {
  353.     switch ( setjmp( save ))
  354.     {
  355. case 0:
  356.       printf ( "We get a zero returned from setjmp on setup.\n\n");
  357.       break;                   /* This is the result from setting up. */
  358.  
  359. case 1:
  360.       printf ( "NORMAL PROGRAM OPERATION\n\n" );
  361.       break;
  362.  
  363. case 2:
  364.       printf ( "WARNING\n\n" );
  365.       break;
  366.  
  367. case 3:
  368.       printf ( "FATAL ERROR PROGRAM TERMINATED\n\nReally Terminate? y/n: " );
  369.       fflush ( stdout );
  370.       scanf ( "%1s", &c );
  371.       c = tolower ( c );
  372.       if ( c == 'y' ) return ( 1 );
  373.       printf ( "\n" );
  374.       break;
  375.  
  376. default:
  377.       printf ( "Should never return here.\n" );
  378.       break;
  379.       }
  380.     process ();
  381.     }
  382.   }
  383.  
  384. process ()
  385. {
  386.   int i;
  387.  
  388.   printf ( "Input a number to simulate an error condition: " );
  389.   fflush ( stdout );
  390.   scanf ( "%d", &i );
  391.   i %= 3;
  392.   i++;                /* So that we call longjmp with  0 < i < 4 */
  393.   longjmp ( save, i);
  394.   }
  395.  
  396.   Although in this silly little demo the call to longjmp is in the same file
  397. as the call to setjmp, this does not have to be the case, and in the practical
  398. situation the call to longjmp will be a long way from the call to setjmp. The
  399. mechanism is that setjmp saves the entire state of the computer's CPU in a
  400. buffer declared in the jmp_buf save; statement and longjmp restores it exactly
  401. with the exception of the register which carries the return value from longjmp.
  402. This value is the same as the second argument in the longjmp call - i in our
  403. little demo. This means, of course, that the stack and frame pointer registers
  404. are reset to the old values and all the local variables being used at the time
  405. of the longjmp call are going to be lost forever. One consequence of this is
  406. that any pointer to memory allocated from the heap will also be lost, and
  407. you will be unable to access the data stored in the buffer. This is what the
  408. jargonauts call "memory leakage", and is really very difficult bug to find.
  409. Your program runs out of dynamic memory long before it should. Take care.
  410. So you have to keep a record of the buffers' addresses and free them
  411. before the call to longjmp.
  412.  
  413. More details later on when we learn about the heap memory allocation routines.
  414.  
  415. Copyright notice:-
  416.  
  417. (c) 1993 Christopher Sawtell.
  418.  
  419. I assert the right to be known as the author, and owner of the
  420. intellectual property rights of all the files in this material,
  421. except for the quoted examples which have their individual
  422. copyright notices. Permission is granted for onward copying,
  423. but not modification, of this course and its use for personal
  424. study only, provided all the copyright notices are left in the
  425. text and are printed in full on any subsequent paper reproduction.
  426.  
  427. --
  428.  +----------------------------------------------------------------------+
  429.  | NAME   Christopher Sawtell                                           |
  430.  | SMAIL  215 Ollivier's Road, Linwood, Christchurch, 8001. New Zealand.|
  431.  | EMAIL  chris@gerty.equinox.gen.nz                                    |
  432.  | PHONE  +64-3-389-3200   ( gmt +13 - your discretion is requested )   |
  433.  +----------------------------------------------------------------------+
  434.